﻿using System.Linq;
using SharpShare.Diagnostics;
using SharpShare.Storage;
using SharpShare.Storage.Security;

namespace SharpShare.Afp.Protocol.Handlers {
    internal class AfpCreateDirectoryRequestHandler : IAfpRequestHandler {
        #region IAfpRequestHandler Members

        public byte CommandCode {
            get { return 6; }
        }

        public AfpResultCode Process(IAfpSession session, DsiHeader dsiHeader, AfpStream requestStream, AfpStream responseStream) {
            requestStream.ReadPadding();

            ushort volumeId = requestStream.ReadUInt16();
            uint directoryId = requestStream.ReadUInt32();
            var path = requestStream.ReadPath().ToList();
            IAfpVolume volume;
            IStorageContainer container = session
                .FindPath(path.Take(path.Count - 1), volumeId, directoryId, out volume)
                .DemandExists()
                .DemandContainer();

            string name = path[path.Count - 1];

            container.GetEffectiveAccess(session).DemandRight(StorageAccessRight.AddContainers);

            IStorageContainer newContainer = container.CreateContainer(name);

            if (newContainer == null) {
                throw new StorageItemNotFoundException();
            }

            if (session.User != null) {
                newContainer.SetOwner(session.User.Id);
                newContainer.SetGroup(session.User.PrimaryGroup);
                newContainer.SetAccessRights(AfpAccessRightsBitmap.OwnerReadWriteExecute);
            }

            uint newContainerId = volume.GetNode(newContainer);

            responseStream.WriteUInt32(newContainerId);

            //try {
            //    container.DateModified = DateTime.Now;
            //} catch { }

            Log.Add(session, EntryType.Debug, "Session '{0}' created container '{1}'.", session, newContainer);

            return AfpResultCode.FPNoErr;
        }

        #endregion
    }
}
